package com.xyz.controller;

import com.xyz.entity.Commodity;
import com.xyz.pojo.Result;
import com.xyz.service.ComService;
import com.xyz.util.JwtUtils;
import io.jsonwebtoken.Claims;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Value;

@RestController
@Slf4j//最主要的问题，token
@RequestMapping("/sell")
public class ComController {

    @Autowired
    private ComService comService;

    @Value("${file.upload-dir}")
    private String uploadDir;//md就是倒错了

    @PostMapping//发布商品
    public Result add(HttpServletRequest req, @RequestParam(value ="file",required = false)MultipartFile file,
                      @RequestParam( "comname") String comname,
                      @RequestParam(value = "price") String price,
                      @RequestParam(value = "status", required = false) String status,
                      @RequestParam(value = "description", required = false) String description,
                      @RequestParam(value = "type", required = false) String type
                    ){
        Commodity commodity = new Commodity();

        commodity.setComname(comname);
        commodity.setPrice(Double.parseDouble(price));
        commodity.setStatus(status);
        commodity.setDescription(description);
        commodity.setType(type);
        if (!file.isEmpty()) {//如果图片不为空
            try {
                // 确保目录存在
                Path uploadPath = Paths.get(uploadDir);
                if (!Files.exists(uploadPath)) {
                    Files.createDirectories(uploadPath);
                }

                // 生成安全的文件名
                String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();

                // 将文件保存到指定目录
                Path filePath = uploadPath.resolve(fileName);
                file.transferTo(filePath.toFile());


                // 保存图片信息到数据库
                commodity.setImage(filePath.toString());

                log.info("文件上传成功:{}", filePath);

            } catch (IOException e) {
                log.info("上传出错");
            }
        } else {
            log.info("没有文件");
        }


        //处理逻辑
        String jwt = req.getHeader(JwtUtils.JWT_HEADER_KEY);

        int id=JwtUtils.getUserIdFromJwt(jwt );
        log.info("用户id:{}",id);

        log.info("新增商品:{}",commodity);


        commodity.setOwnerId(id);//既然如此为什么不直接封装到商品里呢
        //调用service层增加功能
        comService.add(commodity);
        //响应
        return Result.success();
//
    }

    //查询商品，查询所有商品.有几个问题，如果是分页呢，有条件呢。并且一下返回商品所有信息
    @GetMapping
  public Result list(HttpServletRequest req){//@PathVariable Integer ownerid
        String jwt = req.getHeader(JwtUtils.JWT_HEADER_KEY);
        int ownerid=JwtUtils.getUserIdFromJwt(jwt);
        log.info("查询{}所发布的所有商品",ownerid);
      List<Commodity> comlist=comService.list(ownerid);
      return Result.success(comlist);
  }


    //更新商品,最好在前面限制，先返回商品信息，再在此基础上修改
    @PutMapping("/{comid}")//分开传入，而不在商品里
public Result update(@RequestBody Commodity commodity,@PathVariable Integer comid){
        log.info("修改商品：{}",commodity);
        commodity.setComid(comid);
        comService.update(commodity);
        return Result.success();
}


    //删除商品,是这个用户的，才能删除。有几个问题，1.如何防止不是发布者却删除了数据
    @DeleteMapping("/{comid}")
    public Result delete(@PathVariable Integer comid){
        log.info("根据商品ID{}删除数据",comid);
        //调用service层功能,删除商品库的这个商品
        comService.delete(comid);
        //响应
        return Result.success();
    }
}
